//
//  HomeViewModel.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/3.
//

import Foundation
import SwiftUI
class EmojiPictureViewModel : BaseViewModel {
    @Published var tableItem : [EmojiPictureBean] = []
    
    func getData() {
        request(isLoading: false) {
            var listItems:[EmojiPictureBean] = []
            let bean = EmojiPictureBean()
            bean.objectId = "add"
            let list = try await BackupsManager.shared.getDelegateDiary()?.getEmojiPictureList() ?? []
            listItems.append(bean)
            listItems.append(contentsOf: list)
            return listItems
        } suc: { list in
            self.tableItem = list
        } fail: {
            showLog($0.message)
        }
    }
    
    func doAdd(image: UIImage,text: String) {
        request(isLoading: true) {
            let key = UUID().uuidString
            let imageBean = try await LocalConfigImpl().upload(image: image, name: key)
            var bean = EmojiPictureBean()
            bean.path = imageBean.url
            bean.text = text
            bean.width = imageBean.width
            bean.height = imageBean.height
            bean.duration = imageBean.duration
            bean.mimeType = imageBean.mimeType
            bean.sort = 0
            bean = try await BackupsManager.shared.getDelegateDiary()?.addEmojiPicture(bean: bean) ?? EmojiPictureBean()
            return bean
        } suc: { bean in
            self.tableItem.append(bean)
            showToast("添加成功")
        } fail: {
            showLog($0.message)
        }
    }
    
    func doSave(bean: EmojiPictureBean) {
        request(isLoading: true) {
            try await BackupsManager.shared.getDelegateDiary()?.saveEmojiPicture(bean: bean)
            return true
        } suc: { _ in
            self.getData()
            showToast("修改成功")
        } fail: {
            showLog($0.message)
        }
    }
    
    func doDel(index: Int) {
        let item = self.tableItem[index]
        request(isLoading: true) {
            try check((index >= 0),"删除失败")
            try await BackupsManager.shared.getDelegateDiary()?.deleteEmojiPicture(bean: item)
            return true
        } suc: { _ in
            self.getData()
            showToast("删除成功")
        } fail: {
            showLog($0.message)
        }
    }
}
